<template>
  <div>
    <Row class="y_query_right">
      <Cascader v-model="searchParam.collectionCategories" :data="collectionCategoryTree" change-on-select placeholder="采集分类"
                class="y_condition" style="text-align: left;"></Cascader>
      <Input type="text" v-model.trim="searchParam.name" placeholder="产品名称" clearable class="y_condition"></Input>
      <Input type="text" v-model.trim="searchParam.code" placeholder="产品编号" clearable class="y_condition"></Input>
      <Input type="text" v-model.trim="searchParam.sourceCode" placeholder="货源编号" clearable class="y_condition"></Input>
<!--      <Select v-model="searchParam.state" placeholder="状态" clearable class="y_condition" style="text-align: left;">
        <Option :value="3">未上架</Option>
        <Option :value="0">已上架</Option>
      </Select>-->
      <DatePicker type="daterange" :options="datePickerOptions" placement="bottom-end" :editable="false" placeholder="导入时间"
                  @on-change="changeTimeParam" class="y_condition" style="text-align: left; max-width: 200px; width: 200px;">
      </DatePicker>
      <Button type="primary" icon="md-search" @click="search()" class="y_condition">查询</Button>
    </Row>

    <List border class="data-list">
      <template v-if="productList.length > 0">
        <ListItem v-for="(item, index) in productList" :key="item.id" class="list-item">
          <Row class="one-line">
            <Col :span="3" :xxl="3" :xl="4" :lg="5" :md="6" :sm="8" :xs="10">
              <div class="item-img" @click="showBigImage(getProductOriginalImg(item))">
                <img :src="getProductImg(item)" style="max-width: 100%;"/>
              </div>
            </Col>
            <Col :span="21" :xxl="21" :xl="20" :lg="19" :md="18" :sm="16" :xs="14" style="padding-left: 0.5rem">
              <div class="item-top">
                <p style="font-weight: bold;">
                  <Tag :color="getImportStateColor(item)">{{getImportState(item)}}</Tag>
                  {{item.name}}
                </p>
              </div>
              <div class="item-content">
                <div class="one-line">
                  <KeyValueView title="SKU" :value="item.code"></KeyValueView>
                  <KeyValueView title="计费重量" :value="item.countWeight+'g'"></KeyValueView>
                  <KeyValueView title="是否有尺码表" :value="getHasSizeTable(item)"></KeyValueView>
                </div>
                <div class="one-line">
                  <KeyValueView title="导入时间">{{getDateStr(item.createtime)}}</KeyValueView>
                  <KeyValueView title="采集分类" v-if="item.fromProduct!=null && item.fromProduct.categoryNames!=null">{{item.fromProduct.categoryNames.join(" / ")}}</KeyValueView>
                </div>
                <div v-if="item.fromProduct != null" class="one-line">
                  <KeyValueView title="采集货源编号">
                    {{item.fromProduct.pCode}}
                  </KeyValueView>
                  <KeyValueView title="采集标签">
                    <span v-if="item.fromProduct.tags!=null && item.fromProduct.tags.length>0">{{item.fromProduct.tags.join("，")}}</span>
                    <span v-else>无</span>
                  </KeyValueView><br/>
                  <KeyValueView title="采集时间" :value="$tiyBJTime(item.fromProduct.createTime)"></KeyValueView>
                  <KeyValueView title="采集平台" :value="item.fromProduct.from"></KeyValueView>
                  <KeyValueView title="供货商编号" :value="item.fromProduct.shopId"></KeyValueView>
                </div>
                <div>
                  <KeyValueView title="分类" v-if="hasClassified(item)">
                    {{getFirstCategory(item)}}<a href="javascript:void(0)" @click="viewMoreCategories(item)" v-if="item.categoryNames.length > 1" style="margin-left: 10px;">更多</a>
                  </KeyValueView>
                  <KeyValueView title="分类" v-else>无</KeyValueView>
                </div>
              </div>
              <div class="item-bottom">
                <Button type="info" icon="md-create" size="small" @click="showModifyModal(item)">修改</Button>
                <Button type="primary" icon="md-flash" size="small" @click="onlineProduct(item)">上架</Button>
                <Button type="error" icon="md-trash" size="small" @click="deleteProduct(item)">删除</Button>
              </div>
            </Col>
          </Row>
        </ListItem>
      </template>
      <template v-else>
        <ListItem>
          <div class="empty-text">暂无数据</div>
        </ListItem>
      </template>
    </List>

    <div style="text-align: right; margin-top: 20px;">
      <Page :total="page.total" :page-size="page.pageSize" :current="page.pageNum" @on-change="pageNumChange"
            @on-page-size-change="pageSizeChange" :page-size-opts="page.options"
            show-sizer show-elevator show-total></Page>
    </div>

    <!-- 选择分类 -->
    <Modal v-model="status.classifyModal.isShow" title="设置产品分类" :mask-closable="false" :width="600">
      <Form>
        <FormItem label="产品分类" prop="classificationIds">
            <Button type="info" icon="ios-build" ghost @click="showCategoryTreeModal()">选择产品分类</Button>
        </FormItem>
        <div class="cat-list">
          <div v-for="(item, index) in modifyParam.categoryNames" :key="index">
            <span class="tiy_key" style="text-align: left;font-size: 0.5em" v-if="isShowCategoryName(index)">{{item.join(" / ")}}</span>
          </div>
          <div style="width: 100%; text-align: right;" v-if="modifyParam.categoryNames.length>20">
            <Button type="dashed" size="small" @click="toggleAllCategories()">{{categoryButtonTxt}}</Button>
          </div>
        </div>
      </Form>
      <div slot="footer">
        <Button @click="hideClassifyModal()">取消</Button>
        <Button type="primary" @click="saveProductCategories()">保存</Button>
      </div>
    </Modal>

    <!-- 分类树形选择弹窗 -->
    <Modal v-model="status.classifyTreeModal.isShow" title="选择分类" :mask-closable="false">
      <Tree :data="categoryTree" show-checkbox expand-node multiple :select-node="false" ref="Tree" @on-toggle-expand="toggleExpand"></Tree>
      <div slot="footer">
        <Button @click="hideCategoryTreeModal()">取消</Button>
        <Button type="primary" @click="changeCategories()">确定</Button>
      </div>
    </Modal>

    <!-- 显示大图 -->
    <Modal v-model="bigImage.isShow" title="查看图片" footer-hide :width="600">
      <div class="big-img-box">
        <img :src="bigImage.src" alt="图片加载失败">
      </div>
    </Modal>

    <!-- 显示全部分类 -->
    <Modal v-model="allCategories.isShow" title="查看所有分类" footer-hide :width="600">
      <List border>
        <ListItem v-for="(item, index) in allCategories.categoryNames" :key="index" style="margin: 0; padding: 5px 10px;">
          <span class="tiy_key">{{item.join(" / ")}}</span>
        </ListItem>
      </List>
    </Modal>

    <!-- 上架审核编辑 -->
    <Modal v-model="modifyStatus.modalModify.isShow" title="" :closable="modifyStatus.modalModify.closable"
           :mask-closable="false" footer-hide :styles="{top: '20px',bottom:'20px',width:'85%'}">
      <ProductAddEdit ref="AProductAddEdit" @reload-list="search()"></ProductAddEdit>
    </Modal>
  </div>
</template>

<script>
import classifyData from "./js/onSale/onSaleData";
import {
  deleteProduct,
  initPageInfo,
  makeCategoryTree,
  onlineProduct,
  queryProductList,
  saveProductCategories
} from "./js/onSale/onSaleFuns";
import KeyValueView from "../widgets/KeyValueView";
import {createCategoryList, getProductCommonData, isEmpty, isNotEmpty} from "../js/commonUtils";
import Vue from "vue";
import tiyData from "../product/js/list/list_data";
import productData from "./js/product/productData";
import {queryMongoCategories} from "./js/product/productFuns";
import ProductAddEdit from "../product/ProductAddEdit";
import {modifyProduct} from "../product/js/list/add_edit_fun";
import tiyAddEditData from "../product/js/list/add_edit_data";

export default {
  name: "ProductClassify",
  components: {KeyValueView, ProductAddEdit},
  data() {
    return {
      yunPath: this.$store.getters.imgPrefix,
      status: classifyData.tStatus,
      modifyStatus: tiyAddEditData.tStatus,
      searchParam: classifyData.tParam.searchParam,
      productList: classifyData.tData.productList,
      categoryList: classifyData.tData.categoryList,
      categoryTree: classifyData.tData.categoryTree,
      collectionCategoryTree: [],
      modifyParam: classifyData.tParam.modifyParam,
      page: classifyData.tPage.listPage,
      bigImage: {
        isShow: false,
        src: "",
      },
      allCategories: {
        isShow: false,
        categoryNames: [],
      },
      datePickerOptions: productData.dict.datePickerOptions,
      importStates: [
        {value: 0, label: "已加入导入队列"},
        // {value: 1, label: "导入数据中"},
        // {value: 2, label: "导入图片中"},
        {value: 1, label: "正在导入"}, //导入过程不再区分导入数据和导入图片
        {value: 3, label: "数据导入失败"},
        {value: 4, label: "图片导入失败"},
        {value: 5, label: "导入成功"},
      ]
    };
  },
  computed: {
    categoryButtonTxt() {
      return this.status.classifyModal.isShowAllCategories?'点我折叠全部分类......':'点我查看分类列表......';
    },
  },
  methods: {
    search() {
      this.page.pageNum = 1;
      queryProductList(this);
    },
    pageNumChange(pageNum) {
      this.page.pageNum = pageNum;
      queryProductList(this);
    },
    pageSizeChange(pageSize) {
      this.page.pageNum = 1;
      this.page.pageSize = pageSize;
      queryProductList(this);
    },
    hasClassified(item) {
      return item.categoryNames != null && item.categoryNames.length > 0;
    },
    isOnSale(item) {
      return item.state == 0;
    },
    getStateColor(item) {
      if(this.isOnSale(item)) {
        return "success";
      }
      return "warning";
    },
    getProductState(item) {
      if(this.isOnSale(item)) {
        return "已上架";
      }
      return "未上架";
    },
    getImportStateColor(item) {
      if(item.importState == 5) {
        return "success";
      }
      return "error";
    },
    getImportState(item) {
      let element = this.importStates.find(element => item.importState == element.value);
      return element==null?"":element.label;
    },
    getProductOriginalImg(item) {
      if(item.showImage == null) {
        return "";
      }
      return this.yunPath+item.showImage.originalImagePath;
    },
    getProductImg(item) {
      if(item.showImage == null) {
        return "";
      }
      let imgUrl = "";
      if(isNotEmpty(item.showImage.zipImages)) {
        let zipImages = this.$toJson(item.showImage.zipImages);
        for(let zipImg of zipImages) {
          if(zipImg.size == "200w") {
            imgUrl = zipImg.imagePath;
            break;
          }
        }
      }

      if(imgUrl == "") {
        imgUrl = item.showImage.originalImagePath;
      }
      return this.yunPath + imgUrl;
    },
    getDateStr(date) {
      if(isEmpty(date)) {
        return "";
      }
      return Vue.prototype.$tiyBJTime(new Date(date).getTime())
    },
    getFirstCategory(item) {
      if(this.hasClassified(item)) {
        return item.categoryNames[0].join(" / ");
      }
      return "";
    },
    viewMoreCategories(item) {
      if(this.hasClassified(item)) {
        this.allCategories.categoryNames.splice(0);
        this.allCategories.categoryNames.push(...item.categoryNames);
        this.allCategories.isShow = true;
      }
    },
    getHasSizeTable(item) {
      if(item.sizeTable == null || item.sizeTable.length == 0) {
        return "无";
      }
      return "有";
    },
    showBigImage(imgSrc) {
      this.bigImage.src = imgSrc;
      this.bigImage.isShow = true;
    },
    showClassifyModal(item) {
      this.modifyParam.productId = item.id;
      this.modifyParam.categoryIds.splice(0);
      this.modifyParam.categoryNames.splice(0);
      if(item.categoryIds != null) {
        this.modifyParam.categoryIds.push(...item.categoryIds);
      }
      if(item.categoryNames!=null) {
        this.modifyParam.categoryNames.push(...item.categoryNames);
      }
      this.status.classifyModal.isShow = true;
    },
    hideClassifyModal() {
      this.status.classifyModal.isShow = false;
    },
    saveProductCategories() {
      saveProductCategories(this);
    },
    showCategoryTreeModal() {
      this.categoryTree.splice(0);
      let treeData = makeCategoryTree(this.categoryList, this.modifyParam.categoryIds);
      this.categoryTree.push(...treeData);
      this.status.classifyTreeModal.isShow = true;
    },
    hideCategoryTreeModal() {
      this.status.classifyTreeModal.isShow = false;
    },
    isShowCategoryName(index) {
      //小于20行或者点击了显示全部分类按钮
      return index<20 || this.status.classifyModal.isShowAllCategories;
    },
    toggleAllCategories() {
      //点击显示全部分类按钮
      this.status.classifyModal.isShowAllCategories = !this.status.classifyModal.isShowAllCategories
    },
    toggleExpand(data) {
      //展开分类，关闭同一级分类
      if(data.expand && data.level==1){
        tiyData.tData.classificationTree.forEach(function(item,index){
          if(data.value!=item.value&&item.expand==true){
            item.expand=false;
          }
        });
      }
    },
    changeCategories() {
      this.modifyParam.categoryNames.splice(0);
      this.modifyParam.categoryIds.splice(0);
      let nodesLvl1 = this.$refs.Tree.getCheckedAndIndeterminateNodes().filter(item=>item.level==1);
      if(nodesLvl1 == null || nodesLvl1.length == 0) {
        this.$Message.error({content: "请选择分类！", duration: 3, closable: true});
        return;
      }

      for(let nodeLvl1 of nodesLvl1) {
        if(nodeLvl1.children!=null && nodeLvl1.children.length>0) {
          for(let nodeLvl2 of nodeLvl1.children) {
            if(nodeLvl2.checked || nodeLvl2.indeterminate) {
              if(nodeLvl2.children!=null && nodeLvl2.children.length>0) {
                for(let nodeLvl3 of nodeLvl2.children) {
                  if(nodeLvl3.checked) {
                    let catNames = [nodeLvl1.title, nodeLvl2.title, nodeLvl3.title];
                    this.modifyParam.categoryNames.push(catNames);
                    this.modifyParam.categoryIds.push(nodeLvl3.value);
                  }
                }
              }
            }
          }
        }
      }
      this.status.classifyTreeModal.isShow = false;
    },
    changeTimeParam(dateArr, type) {
      if(isNotEmpty(dateArr[0])){
        this.searchParam.startTime =this.$tiyQueryTime(new Date(dateArr[0]+' 00:00:00').getTime());
        this.searchParam.endTime = this.$tiyQueryTime(new Date(dateArr[1]+' 23:59:59').getTime());
      }
    },
    showModifyModal(item) {
      modifyProduct(this, tiyAddEditData, item.id, true);
    },
    onlineProduct(item) {
      onlineProduct(this, item.id);
    },
    deleteProduct(item) {
      deleteProduct(this, item.id);
    }
  },
  mounted() {
    getProductCommonData(this, this.categoryList, [3], true, createCategoryList);
    queryMongoCategories(this, this.collectionCategoryTree);
    initPageInfo();
  }
}
</script>

<style scoped lang="less">
@import  (once,optional)  "../css/base.less";
.data-list {
  margin-top: 1rem;
  text-align: left;
  .list-item {
    .flex-colum-wrap;
    justify-items: left;
    align-items: start;
    .item-img {
      width: 130px;
      text-align: center;
      margin: 0 auto;
    }
    .item-top{
      width: 100%;
      margin-bottom: 5px;
      .flex-row-wrap;
      justify-content: space-between;
    }
    .item-content {
      margin-bottom: 35px;
      text-align: left;
      line-height: 25px;
    }
    .item-bottom{
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      display: block;
      //padding: 0 1rem 0.5rem 0;
      cursor: pointer;
      text-align: right;
      button {
        margin-left: 0.5rem;
      }
    }
  }
}
.empty-text {
  width: 100%;
  text-align: center;
  color: #ccc;
}
.one-line {
  width: 100%;
}
.cat-list {
  width: 80%;
  margin: 0 auto;
}
.big-img-box {
  width: 100%;
  min-height: 500px;
  text-align: center;
  img {
    max-width: 100%;
    vertical-align: middle;
  }
}
</style>
